<!--角色选择框-->
<template>
  <div>
    <div class="info-title"
      >{{ title }} <a-button v-if="isActions" type="primary" :disabled="disabled" @click="btnClick">{{ t('select') }}</a-button></div
    >

    <BasicTable v-bind="config" :dataSource="dataSource">
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <template #tempPosition="{ record }">
        <div style="display: flex; align-items: center; font-size: 18px">
          <JTreeSelect
            v-model:value="tempPositionObj[record.id]"
            v-bind="{
              dict: 'asset_position,position_name,id',
              pidField: 'pid',
              condition: JSON.stringify(tempPosition.condition),
              pidValue: '0',
              hasChildField: 'has_child',
            }"
          /><vertical-align-bottom-outlined style="margin-left: 4px; cursor: pointer" @click="dowmClick(record.id)" />
        </div>
      </template>
    </BasicTable>
    <SelectAssetModal @register="regModal" @select="setValue" :queryParam="queryParam" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, computed, watch } from 'vue';
  import { selectProps } from '/@/components/Form/src/jeecg/props/props';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { BasicColumn, ActionItem } from '/@/components/Table';
  import type { FormProps } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import SelectAssetModal from './SelectAssetModal.vue';
  import JTreeSelect from '@/components/Form/src/jeecg/components/JTreeSelect.vue';
  import { VerticalAlignBottomOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t: common } = useI18n('common');
  const { t } = useI18n('asset.assetInfo.fields');
  const [regModal, { openModal }] = useModal();
  const emits = defineEmits(['select', 'delete']);
  const props = defineProps({
    ...selectProps,
    title: { type: String, default: '资产信息' },
    hasSelection: { type: Boolean, default: true },
    isActions: { type: Boolean, default: true },
    disabled: { type: Boolean, default: false },
    showUser: { type: Boolean, default: false },
    assetDataList: { type: Array, default: () => [] },
    queryParam: { type: Object, default: () => ({}) },
    tempPosition: {
      type: Object,
      default: () => ({ show: false }),
    },
  });

  const dataSource = computed(() => {
    return [...props.assetDataList, ...tableData.value];
  });

  //查询form
  const formConfig: Partial<FormProps> = {
    //labelWidth: 220,
    baseColProps: {
      xs: 24,
      sm: 24,
      md: 24,
      lg: 14,
      xl: 14,
      xxl: 14,
    },
    schemas: [
      {
        label: t('name'),
        field: 'name',
        component: 'JInput',
      },
    ],
  };

  //定义表格列
  const columns: BasicColumn[] = [
    {
      title: t('name'),
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: t('cartegory'),
      align: 'center',
      dataIndex: 'cartegory_dictText',
    },
    {
      title: t('user'),
      align: 'center',
      width: 120,
      dataIndex: 'user_dictText',
      ifShow: props.showUser,
    },
    {
      title: t('position'),
      align: 'center',
      width: 120,
      dataIndex: 'position_dictText',
    },

    {
      title: t('returnPosition'),
      align: 'center',
      dataIndex: 'tempPosition',
      slots: { customRender: 'tempPosition' },
      ifShow: props.tempPosition.show,
    },
    {
      title: t('code'),
      align: 'center',
      dataIndex: 'code',
    },
    {
      title: t('user'),
      align: 'center',
      width: 120,
      dataIndex: 'custodyDepartment_dictText',
    },
    {
      title: t('custodyDepartment'),
      align: 'center',
      width: 100,
      slots: { customRender: 'action' },
      ifShow: props.isActions,
    },
  ];
  //表格配置
  const config: any = {
    canResize: false,
    bordered: true,
    size: 'small',
    useSearchForm: false,
    rowKey: unref(props).rowKey,
    formConfig,
    columns,
  };
  /**
   * 操作栏
   */
  function getTableAction(record) {
    const action: { [key: string]: ActionItem } = {
      EDIT: {
        label: common('editText'),
        type: 'primary',
        disabled: props.disabled,
        onClick: btnClick,
      },
      DELETE: {
        label: '删除',
        danger: true,
        disabled: props.disabled || props.assetDataList.length <= 1,
        popConfirm: {
          title: '是否确认删除',
          placement: 'left',
          confirm: () => {
            emits('delete', record);
          },
        },
      },
    };
    return record?.isEdit ? [action.EDIT] : [action.DELETE];
  }
  const tempPositionObj: any = ref({});
  watch(
    () => props.assetDataList,
    () => {
      props.assetDataList.forEach((item: any) => {
        if (!tempPositionObj.value[item.id]) {
          tempPositionObj.value[item.id] = item.tempPosition;
        }
      });
    },
    {
      immediate: true,
    }
  );
  const dowmClick = (id) => {
    let position = '';
    let isCurrent = false;
    dataSource.value.forEach((item) => {
      if (isCurrent) {
        tempPositionObj.value[item.id] = position;
      }
      console.log(tempPositionObj.value, 'itemitem');
      if (item.id === id) {
        position = tempPositionObj.value[id];
        isCurrent = true;
      }
    });
  };
  const tableData = ref<any[]>([]);
  function setValue({ data, id }) {
    console.log(data, id, 'setValue');
    tableData.value = data.map((item) => {
      // tempPositionObj.value[item.id] = tempPositionObj.value[item.id] || '';
      return { ...item, isEdit: true };
    });
    emits('select', { data, id: [...props.assetDataList.map(({ id }) => id), ...id] });
  }

  const getSelectedData = () => {
    tableData.value.forEach((item) => {
      delete item.isEdit;
    });
    const returnData = [...unref(props.assetDataList), ...unref(tableData)];
    returnData.forEach((item) => {
      item.tempPosition = tempPositionObj.value[item.id];
    });
    return { data: returnData, id: returnData.map(({ id }) => id) };
  };

  function btnClick() {
    openModal(true, {
      isUpdate: false,
    });
  }
  defineExpose({
    getSelectedData,
  });
</script>
<style scoped>
  .info-title {
    font-size: 15px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    padding-right: 6px;
  }
</style>
